package 
{	
	import Common.FrameLimiter;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.display.StageQuality;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.TimerEvent;
	import flash.system.Security;
	import flash.utils.getTimer;
	import flash.utils.Timer;
	import Game.GameCamera;
	import Game.GameStates.EditorState;
	import Game.GameStates.MainMenuState;
	import Game.Online.Messages.MessagesHandler;
	import Game.Online.OnlineManager;
	import Game.Windows.DebugWindow;
		
	import Common.Input;
	import Common.Managers.SwfManager;
	
	import Game.GameElements.Tank;
	import Game.World;
	import Game.AI.EnemyTankAI;
	import Game.Effects.Explosion;
	import Game.GameElements.Rocket;
	import Game.GameStates.BaseState;
	import Game.GameStates.GameState;
	import Game.Windows.LoadingWindow;
	
	/**
	 * ...
	 * @author Yevgeniy Logachev
	 */
	[SWF(width='640', height = '512', backgroundColor='#000000', frameRate='60')]
	public class Main extends MovieClip
	{
		private static var m_mainSprite:Sprite 		= null;
		private static var m_state:BaseState 		= null;
				
		public function Main():void 
		{
			// Create main sprite
			m_mainSprite = new Sprite();
			this.addChild(m_mainSprite);
			
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		public static function get mainSprite():Sprite
		{
			return m_mainSprite;
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			stage.scaleMode = StageScaleMode.NO_SCALE;
			Input.register(stage);
			
			//m_state = new MainMenuState();
			startMenu();
			//m_state = new GameState(1);
			
			addEventListener(Event.ENTER_FRAME, update, false, 0, true);
		}
		
		public static function startGame():void
		{
			m_state = new GameState(1);
		}
		
		public static function startMenu():void
		{
			m_state = new MainMenuState();
		}
		
		public static function startEditor():void
		{
			m_state = new EditorState();
		}
		
		public static function get currentState():BaseState
		{
			return m_state;
		}
		
		public function update(e:Event):void
		{
			//clear for rendering
			m_mainSprite.graphics.clear();
			if (Settings.enableOnline && OnlineManager.instance.connection != null)
			{
				OnlineManager.instance.connection.handleData();
			}
			
			if (Settings.enableOnline)
			{
				MessagesHandler.update();
			}
			
			//DebugWindow.instance.addLine("init: " + m_state.isInit);
			
			if (m_state != null && m_state.isInit && OnlineManager.instance.isLoggedIn)
			{
				m_state.update();
			}
		}
	}
}